package com.yj.idempotence.aop;

import com.yj.idempotence.annotation.CheckToken;
import com.yj.idempotence.dao.TokenImpl;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Slf4j
@Component
public class CheckTokenAop {

    @Autowired
    TokenImpl tokenService;

    @Pointcut("@annotation(com.yj.idempotence.annotation.CheckToken)")
    public void checkPoint(){}


    @Before(value = "checkPoint()")
    public void before(JoinPoint joinPoint) throws Throwable {

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request =    ((ServletRequestAttributes)requestAttributes).getRequest();

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        CheckToken annotation = method.getAnnotation(CheckToken.class);
        log.info("---------------------------》");
        log.info("signature；{}",signature);
        log.info("method；{}",method);
        if (annotation!=null){
            boolean checkToken = tokenService.checkToken(request);
            log.info("获取到的checkToken：{}",checkToken);
        }

    }

}
